#include <jni.h>
#include <string>
#include "logutil.h"
#include "field_test.h"
#include "method_test.h"


//动态注册
static jstring dynamicRegister(JNIEnv *env, jobject);

extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env = nullptr;
    if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return JNI_EVERSION;
    }

    LOGI("JNI_OnLoad()");
    jclass clazz = env->FindClass("com/example/jniexample/MainActivity");
    if (clazz == nullptr) {
        return JNI_ERR;
    }
    JNINativeMethod methods[] = {
            {"dynamicRegister",    "()Ljava/lang/String;",                   (void *) dynamicRegister},
            {"accessFieldA",       "()I",                                    (void *) accessFieldA},
            {"writeFieldA",        "(I)V",                                   (void *) writeFieldA},
            {"accessStaticFieldB", "()Ljava/lang/String;",                   (void *) accessStaticFieldB},
            {"writeStaticFieldB",  "(Ljava/lang/String;)V",                  (void *) writeStaticFieldB},
            {"invokeStaticMethod", "(Ljava/lang/String;)Ljava/lang/String;", (void *) invokeStaticMethod},
            {"invokeMethod",       "(II)I",                                  (void *) invokeMethod}
    };
    jint rc = env->RegisterNatives(clazz, methods, sizeof(methods) / sizeof(JNINativeMethod));
    if (rc != JNI_OK) {
        return rc;
    }
    LOGI("methods.size:%d", sizeof(methods) / sizeof(JNINativeMethod));
    return JNI_VERSION_1_6;
}


extern "C" JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) {
    LOGI("JNI_OnUnload()");
}

//静态注册
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_jniexample_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

jstring dynamicRegister(JNIEnv *env, jobject) {
    std::string hello = "dynamicRegister";
    return env->NewStringUTF(hello.c_str());
}




